<template>
  <div class="sign-tabs">
    <!-- 标签切换：正常签到 / 实践预约签到 -->
    <el-tabs
      v-model="activeTab"
      type="card"
      style="margin-bottom: 16px;"
      @tab-click="handleTabChange"
    >
      <el-tab-pane label="正常签到" name="normal"></el-tab-pane>
      <el-tab-pane label="实践预约签到" name="practice"></el-tab-pane>
    </el-tabs>

    <!-- 引入签到表格组件 -->
    <sign-table
      :class-id="classId"
      :active-tab="activeTab"
      :normal-sign-list="normalSignList"
      :practice-sign-list="practiceSignList"
      :search-form="searchForm"
      @update:selected-rows="rows => $emit('update:selected-rows', rows)"
      @update:filtered-list="list => $emit('update:filtered-list', list)"
      @show-sign-detail="params => $emit('show-sign-detail', params)"
    />
  </div>
</template>

<script>
import SignTable from './signTable.vue';
import { selectAllCheckinDetailsByClassId } from "@/api/training/ClassCheckin";
import { getStudentPracticeCheckIn } from "@/api/training/practiceClassStudent";
// 补充日期格式化方法（核心解决点）
Date.prototype.format = function(fmt) {
  var o = {
    "M+": this.getMonth() + 1, // 月份
    "d+": this.getDate(), // 日
    "H+": this.getHours(), // 小时
    "m+": this.getMinutes(), // 分
    "s+": this.getSeconds(), // 秒
    "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
    "S": this.getMilliseconds() // 毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
    }
  }
  return fmt;
};
export default {
  name: "SignTabs",
  components: { SignTable },
  props: {
    classId: {
      type: String,
      required: true
    },
    searchForm: {
      type: Object,
      default: () => ({
        name: "",
        phone: "",
        idCard: "",
        signStatus: ""
      })
    }
  },
  data() {
    return {
      activeTab: "normal",
      normalSignList: [],
      practiceSignList: []
    };
  },
  created() {
  },
  watch:{
    classId:{
      handler(newVal){
        this.getTrainingList();
      }
    }
  },
  methods: {
    async getTrainingList() {
      this.$emit('loading', true);
      try {
        // 获取正常签到数据
        const res = await selectAllCheckinDetailsByClassId({
          trainingClassId: this.classId
        });
        this.normalSignList = this.formatNormalSignData(res.rows);

        // 获取实践预约签到数据
        const res1 = await getStudentPracticeCheckIn(this.classId);
        this.practiceSignList = this.formatPracticeSignData(res1.rows);
      } catch (error) {
        console.error("获取签到数据失败：", error);
        this.$message.error("获取签到数据失败，请重试");
      } finally {
        this.$emit('loading', false);
      }
    },
    formatNormalSignData(rawList) {
      if (!rawList || rawList.length === 0) return [];

      return rawList.map(student => {
        const { studentId, studentName, idNumber, phoneNumber, activityCheckins = [] } = student;

        const signDates = activityCheckins.map(item => {
          const start = item.checkinStartTime ? new Date(item.checkinStartTime).format("yyyy-MM-dd HH:mm") : "";
          const end = item.checkinEndTime ? new Date(item.checkinEndTime).format("HH:mm") : "";
          return start ? `${start}-${end}` : "未知时段";
        });

        const signStatuses = activityCheckins.map(item => {
          const statusMap = { 0: "未签到", 1: "已签到", 2: "迟到", 3: "早退" };
          return statusMap[item.checkinStatus] || "未知状态";
        });

        const signDetails = activityCheckins.map(item => {
          const checkinTime = item.actualCheckinTime
            ? new Date(item.actualCheckinTime).format("yyyy-MM-dd HH:mm:ss")
            : "";
          return {
            time: checkinTime || "未签到",
            device: item.checkinDevice || "未知设备"
          };
        });

        return {
          id: studentId,
          name: studentName,
          idCard: idNumber || "无",
          phone: phoneNumber || "无",
          signDates,
          signStatuses,
          signDetails,
          remark: student.checkinRemark || ""
        };
      });
    },
    formatPracticeSignData(rawList) {
      if (!rawList || rawList.length === 0) return [];

      return rawList.map((student, index) => {
        const {
          studentName,
          idNumber,
          phoneNumber,
          practiceCheckInItems = [],
          checkInCount,
          notCheckInCount
        } = student;

        const signDates = practiceCheckInItems.length > 0
          ? practiceCheckInItems.map(item => item.practiceName || `实践项 ${index + 1}`)
          : ["暂无实践签到项"];

        const signStatuses = practiceCheckInItems.length > 0
          ? practiceCheckInItems.map(item => {
              return item.checkStatusDesc === "-" ? "未签到" : item.checkStatusDesc;
            })
          : ["未签到"];

        const signDetails = practiceCheckInItems.length > 0
          ? practiceCheckInItems.map(() => ({
              time: "未记录",
              device: "未知设备"
            }))
          : [{ time: "未记录", device: "未知设备" }];

        const firstPracticeId = practiceCheckInItems[0]?.practiceAppointmentId || index;
        const uniqueId = `practice-${firstPracticeId}-${studentName}`;

        return {
          id: uniqueId,
          name: studentName,
          idCard: idNumber || "无",
          phone: phoneNumber || "无",
          signDates,
          signStatuses,
          signDetails,
          checkInCount: checkInCount || 0,
          notCheckInCount: notCheckInCount || 0,
          remark: ""
        };
      });
    },
    handleTabChange() {
      this.$emit('tab-change', this.activeTab);
    }
  }
};
</script>

<style scoped>
.sign-tabs {
  width: 100%;
}
</style>
